<!-- 蓄水池控制-历史记录 -->
<template>
  <div class="impoundControlHistory">
    <div class="searchBox">
      <el-form inline :model="form">
        <el-form-item>
          <el-input v-model="form.keyWord" placeholder="设备名称或设备编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.operation" placeholder="指令类型" clearable style="width: 100px">
            <el-option label="开" value="开"></el-option>
            <el-option label="关" value="关"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" class="search" @click="query">查询</el-button>
          <el-button type="primary" class="reset" icon="el-icon-refresh-left" plain @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="con">
      <div class="tableBox">
        <Htable
          ref="Htable"
          :isLoading="isLoading"
          :data="tableData"
          :total="total"
          :pageSize.sync="pageSize"
          :pageNum.sync="current"
          :sequence="sequence"
          :reserveSelection="reserveSelection"
          :row-key="getRowKey"
          @lazyLoad="getList"
          @select="handleCheckChange"
          height="100%"
        >
          <el-table-column align="center" prop="reservoirName" label="所在蓄水池"></el-table-column>
          <el-table-column align="center" prop="deviceName" label="阀门名称"></el-table-column>
          <el-table-column align="center" prop="operation" label="操作动作"></el-table-column>
          <el-table-column align="center" prop="operationTime" label="控制时间" width="150px"></el-table-column>
          <el-table-column align="center" prop="operationResult" label="控制结果">
            <template slot-scope="{ row }">
              <span v-if="row.operationResult == 0">控制成功</span>
              <span v-else-if="row.operationResult == 1">控制失败</span>
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="userName" label="操作人"></el-table-column>
          <el-table-column align="center" prop="operationPhone" label="手机号"></el-table-column>
        </Htable>
      </div>
      <div class="selectBox">
        <div class="selectTitle">已选择设备：</div>
        <div class="selectArea">
          <el-tag :key="index" v-for="(tag, index) in tableSelect">
            {{ tag.deviceName }}
          </el-tag>
        </div>
        <div class="selectBtns">
          <el-button type="success" size="mini" @click="handleOpen"><i class="iconfont icon-youxiao"></i>一键开启</el-button>
          <el-button type="danger" size="mini" @click="handleClose"><i class="iconfont icon-wuxiao"></i>一键关闭</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getValveHistory, impoundDeviceControl } from '@/wsgq/api/equipControl'
import { msgModuleAuditState } from '@/index/constants/staticSelectionData'

export default {
  name: 'ImpoundControlHistory',
  data() {
    return {
      form: {
        keyWord: '',
        operation: '',
        time: []
      },
      tableSelect: [], // 表格批量选择数据
      isLoading: false,
      tableData: [],
      total: 0,
      pageSize: 50,
      current: 1,
      sequence: false,
      reserveSelection: true
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    async getList() {
      const params = {
        keyWord: this.form.keyWord,
        operation: this.form.operation,
        type: 1,
        stp: this.form.time ? this.form.time[0] : '',
        etp: this.form.time ? this.form.time[1] : '',
        pageSize: this.pageSize,
        current: this.current
      }
      const res = await getValveHistory(params)
      this.tableData = res.data.records
      this.total = Number(res.data.total)
      this.$refs.Htable.doLayout()
    },
    query() {
      this.current = 1
      this.tableSelect = []
      this.$refs.Htable.clearSelection()
      this.getList()
    },
    reset() {
      // 重置
      this.form = {
        keyWord: '',
        operation: '',
        time: []
      }
      this.current = 1
      this.tableSelect = []
      this.$refs.Htable.clearSelection()
      this.getList()
    },
    getRowKey(row) {
      return row.deviceHistoryDataId
    },
    handleCheckChange(selection, row) {
      // 表格行内复选框勾选
      // console.log(selection, row)
      // console.log(this.tableSelect)
      if (this.tableSelect.filter((item) => item.deviceId === row.deviceId).length > 0) {
        this.$refs.Htable.toggleRowSelection(row, false)
        if (this.tableSelect.filter((item) => item.deviceHistoryDataId === row.deviceHistoryDataId).length == 0) {
          this.$message.error('设备已选择！')
        }
        this.tableSelect = selection.filter((item) => {
          return item.deviceHistoryDataId !== row.deviceHistoryDataId
        })
      } else {
        this.$refs.Htable.toggleRowSelection(row, true)
        this.tableSelect.push(row)
      }
    },
    handleCloseTag(tag) {
      // 右侧tag标签点击删除，去掉此数据，并且左侧表格不勾选
      this.tableSelect = this.tableSelect.filter((filterItem) => filterItem !== tag)
      this.$refs.Htable.toggleRowSelection(tag, false)
    },
    handleOpen() {
      // 一键开启
      if (this.tableSelect.length === 0) {
        this.$message.error('请选择要操作的数据！')
        return false
      }
      let all = '' // 所有选中的设备名称
      let open = '' // 所有已开启状态的设备
      let openNum = 0 // 所有已开启状态的设备个数
      let off = '' // 正处于离线状态的设备
      let offNum = 0 // 正处于离线状态的设备个数
      let error = '' // 正处于故障状态的设备
      let errorNum = 0 // 正处于故障状态的设备个数
      let close = '' // 正处于关闭状态的设备
      let closeNum = 0 // 正处于关闭状态的设备
      let closeArry = [] // 存在关闭状态的设备List
      this.tableSelect.forEach((item) => {
        all += `${item.deviceName}（${item.deviceId}）、`
        if (item.valveStatus === '开') {
          // 已开启
          open += `${item.deviceName}（${item.deviceId}）、`
          openNum++
        }
        if (Number(item.activeStatus) === 0 || item.valveStatus === '未知' || item.valveStatus === '未使用') {
          // 离线
          off += `${item.deviceName}（${item.deviceId}）、`
          offNum++
        }
        if (item.valveStatus === '异常') {
          // 故障
          error += `${item.deviceName}（${item.deviceId}）、`
          errorNum++
        }
        if (item.valveStatus === '关') {
          // 关闭
          close += `${item.deviceName}（${item.deviceId}）、`
          closeNum++
          closeArry.push(item)
        }
      })
      const msg = [
        `您选择的是${all}共计${this.tableSelect.length}个设备，其中`,
        `【${open}】${openNum}个设备已处于开启状态，`,
        `【${off}】${offNum}个设备已处于离线状态，`,
        `【${error}】${errorNum}个设备已处于故障状态;`,
        `本次一键开启只开启【${close}】${closeNum}个设备。`
      ]
      this.openMessageBox('一键开启提示', msg).then((params) => {
        const { action, instance, done } = params
        if (action === 'confirm') {
          if (closeArry.length > 0) {
            const deviceIds = []
            closeArry.forEach((item) => {
              deviceIds.push(item.deviceId)
            })
            const resParams = {
              deviceIds,
              statusKeyword: 'ON'
            }
            impoundDeviceControl(resParams).then((res) => {
              if (res.code === '0') {
                this.$message.success('设备开启成功！')
                this.getList()
                this.tableSelect = []
                this.$refs.Htable.clearSelection()
                this.$emit('refreshList')
              } else {
                this.$message.error(res.msg)
              }
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            this.$message.error('请选择关闭状态的阀门进行操作！')
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            return false
          }
        }
      })
    },
    handleClose() {
      // 一键关闭
      if (this.tableSelect.length === 0) {
        this.$message.error('请选择要操作的数据！')
        return false
      }
      let all = '' // 所有选中的设备名称
      let close = '' // 正处于关闭状态的设备
      let closeNum = 0 // 正处于关闭状态的设备
      let off = '' // 正处于离线状态的设备
      let offNum = 0 // 正处于离线状态的设备个数
      let error = '' // 正处于故障状态的设备
      let errorNum = 0 // 正处于故障状态的设备个数
      let open = '' // 所有已开启状态的设备
      let openNum = 0 // 所有已开启状态的设备个数
      let openArry = [] // 存在开启状态的设备List
      this.tableSelect.forEach((item) => {
        all += `${item.deviceName}（${item.deviceId}）、`
        if (item.valveStatus === '开') {
          // 已开启
          open += `${item.deviceName}（${item.deviceId}）、`
          openNum++
          openArry.push(item)
        }
        if (Number(item.activeStatus) === 0 || item.valveStatus === '未知' || item.valveStatus === '未使用') {
          // 离线
          off += `${item.deviceName}（${item.deviceId}）、`
          offNum++
        }
        if (item.valveStatus === '异常') {
          // 故障
          error += `${item.deviceName}（${item.deviceId}）、`
          errorNum++
        }
        if (item.valveStatus === '关') {
          // 关闭
          close += `${item.deviceName}（${item.deviceId}）、`
          closeNum++
        }
      })
      const msg = [
        `您选择的是${all}共计${this.tableSelect.length}个设备，其中`,
        `【${close}】${closeNum}个设备已处于关闭状态，`,
        `【${off}】${offNum}个设备已处于离线状态，`,
        `【${error}】${errorNum}个设备已处于故障状态;`,
        `本次一键关闭只关闭【${open}】${openNum}个设备。`
      ]
      this.openMessageBox('一键关闭提示', msg).then((params) => {
        const { action, instance, done } = params
        if (action === 'confirm') {
          if (openArry.length > 0) {
            const deviceIds = []
            openArry.forEach((item) => {
              deviceIds.push(item.deviceId)
            })
            const resParams = {
              deviceIds,
              statusKeyword: 'OFF'
            }
            impoundDeviceControl(resParams).then((res) => {
              if (res.code === '0') {
                this.$message.success('设备关闭成功！')
                this.getList()
                this.tableSelect = []
                this.$refs.Htable.clearSelection()
                this.$emit('refreshList')
              } else {
                this.$message.error(res.msg)
              }
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            this.$message.error('请选择开启状态的阀门进行操作！')
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            return false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/_css/common/baseCssVar.scss';
.impoundControlHistory {
  width: 100%;
  height: 100%;
  padding: 10px;
  .con {
    width: 100%;
    height: calc(100% - 52px);
    display: flex;
    justify-content: space-between;
    .tableBox {
      width: 69%;
      height: 100%;
    }
    .selectBox {
      width: 30%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .selectTitle {
        height: 30px;
        line-height: 30px;
      }
      .selectArea {
        width: 100%;
        height: calc(100% - 70px);
        border: 1px solid #d1d1d1;
        border-radius: 5px;
        padding: 10px;
        overflow-y: auto;
      }
      .selectBtns {
        text-align: center;
        .iconfont {
          padding-right: 5px;
        }
      }
    }
  }
  /deep/ .myTable_wrapper {
    padding-top: 0;
  }
  /deep/ .el-tag {
    margin: 0 5px 5px 0;
  }
  /deep/ .myTable_wrapper_page {
    justify-content: center;
  }
  /deep/ .el-table__header tr th:nth-child(1) .cell {
    display: none;
  }
}
</style>
